"""字段配置API"""
from typing import List
from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session

from app.database import get_db
from app.services.field_config_service import FieldConfigService
from app.services.scan_task_service import ScanTaskService
from app.schemas.common import ResponseBase, PaginatedResponse
from app.models.field_config import FieldConfig

router = APIRouter()


@router.get("/tasks/{task_id}/field-configs", response_model=PaginatedResponse)
async def get_field_configs_by_task(
    task_id: int,
    category: str = Query(None, description="字段分类: record_extension/issue_extension"),
    db: Session = Depends(get_db),
):
    """获取任务的字段配置列表"""
    # 验证任务是否存在
    task_service = ScanTaskService(db)
    task = task_service.get_by_id(task_id)
    if not task:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=f"扫描任务 {task_id} 不存在",
        )
    
    service = FieldConfigService(db)
    
    if category:
        configs = service.get_by_category(task_id, category)
    else:
        configs = service.get_by_task_id(task_id)
    
    # 转换为字典格式
    config_data = []
    for config in configs:
        config_data.append({
            "id": config.id,
            "task_id": config.task_id,
            "field_name": config.field_name,
            "display_name": config.display_name,
            "field_type": config.field_type,
            "field_category": config.field_category,
            "display_order": config.display_order,
            "show_in_list": config.show_in_list,
            "show_in_detail": config.show_in_detail,
            "searchable": config.searchable,
            "sortable": config.sortable,
            "required": config.required,
            "default_value": config.default_value,
            "help_text": config.help_text,
            "created_at": config.created_at.isoformat() if config.created_at else None,
            "updated_at": config.updated_at.isoformat() if config.updated_at else None,
        })
    
    return PaginatedResponse(
        code=200,
        message="success",
        data=config_data,
        total=len(config_data),
        skip=0,
        limit=len(config_data),
    )

